package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.HuanXin.HuanXinTemplate;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.vo.dbvo.TanHuaVo;
import com.itheima.vo.dbvo.UserInfoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.dbvo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserManager {

    @DubboReference
    private UserService userService;
    @DubboReference
    private UserInfoService userInfoService;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //保存用户
    public ResponseEntity save(User user) {
        return ResponseEntity.ok(userService.save(user));
    }

    //根据手机查询用户
    public ResponseEntity findByPhone(String phone) {
        return ResponseEntity.ok(userService.findByPhone(phone));
    }

    //发送短信
    public void sendSms(String phone) {
        //生成6位随机数
        String smsCode = RandomUtil.randomNumbers(6);
        smsCode="123456";
        //调用阿里云发送
      //  smsTemplate.sendSms(phone,smsCode);
        //将验证码存储到redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone,smsCode, Duration.ofMinutes(5));

    }

    //注册 or 登录
    public ResponseEntity loginVerification(String phone, String verificationCode) {
        //声明一个返回结果
        HashMap<String, Object> resultmap = new HashMap<>();
        //获取redis的验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        //比对验证码
        if (!StrUtil.equals(verificationCode,codeFromRedis)){
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
         //根据手机号查询用户
        User user = userService.findByPhone(phone);
        //判断用户是否存在
        if (user!=null){
            resultmap.put("isNew",false);
        }else {
            resultmap.put("isNew",true);
            //帮新用户注册
             user = new User();
             user.setPhone(phone);
             user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long newUserId = userService.save(user);
            user.setId(newUserId);
            //注册到环信
            huanXinTemplate.register("HX"+newUserId);
        }
        //.使用jwt制作令牌
        //清除密码
        user.setPassword(null);
        //将user转成map集合
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        //再将map集合制作成令牌
        String token = JwtUtil.createToken(claims);
        //再将User转成json格式
        String json = JSON.toJSONString(user);
        //再将json格式的User存到redis中
         stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token,json,Duration.ofDays(7));

         //再将短信验证码清除
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE+phone);

        //返回结果
        resultmap.put("token",token);
        return ResponseEntity.ok(resultmap);
    }

    // 完善用户基础信息
    public void loginReginfo(UserInfo userInfo, String token) {
     //解析token获取user对象
        User  user  =findUserByToken(token);
     //给userinfo 设置userid
        userInfo.setId(user.getId());

        //调用rpc保存
         userInfoService.save(userInfo);
    }

    // 解析token获取user对象
    public User findUserByToken(String token){
        //1.对token进行非空判断
        if (StrUtil.isEmpty(token)){
            return null;
        }
        //2.获取redis的user对象
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

        //3.对json进行非空判断
        if (StrUtil.isEmpty(json)){
            return null;
        }

        //4.转化为user对象
        User user = JSON.parseObject(json, User.class);

        //5.对redis的user进行续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token,json,Duration.ofDays(7));

        return user;
    }

    //完善用户头像
    public ResponseEntity loginReginfoHead(MultipartFile headPhoto, String token) throws IOException {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        //2.人脸检测
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        //3.人脸判断
        if (detect==false){
            return  ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        //4.上传图片到oss
        String prcurl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //5.组装userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId()); //用户id
        userInfo.setAvatar(prcurl);//头像
        userInfo.setCoverPic(prcurl);//背景图片

        //6.调用rpc更新
        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);

    }
    // 根据id查询userInfo用户信息
    public ResponseEntity findUserInfoVo(Long userID) {
      // 1.调用rpc查询userInfo
        UserInfo userInfo = userInfoService.findUserInfoById(userID);
        //封装userInfo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo,userInfoVo);
        //返回
        return ResponseEntity.ok(userInfoVo);

    }

    public void updateUserInfoVo(UserInfo userInfo, String token) {
        //解析token获取对象
        User user = findUserByToken(token);
        //获取对象的id并设置到userinfo中
        userInfo.setId(user.getId());
        //调用rpc完成更新
        userInfoService.update(userInfo);
    }


    public ResponseEntity showTanhua() {
        //获取当前线程饿用户id
        Long userId = UserHolder.get().getId();

        //去查询userInfo
        List<UserInfo> userInfoList = userInfoService.findByUserInfo();
        List<TanHuaVo> tanHuaVoList = new ArrayList<>();


        if (CollectionUtil.isNotEmpty(userInfoList)) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getId() == userId) {
                    continue;
                }
                TanHuaVo tanHuaVo = new TanHuaVo();
                tanHuaVo.setId(userInfo.getId().intValue());
                tanHuaVo.setAvatar(userInfo.getAvatar());
                tanHuaVo.setAge(userInfo.getAge());
                tanHuaVo.setNickname(userInfo.getNickname());
                tanHuaVo.setTags(userInfo.getTags().split(""));
                tanHuaVoList.add(tanHuaVo);
            }
        }

        return ResponseEntity.ok(tanHuaVoList);
    }
}




